package main

import (
	"bufio"
	"fmt"
	"github.com/urfave/cli"
	"log"
	"os"
	"strconv"
	"strings"
	"time"
)

func addMemo(c *cli.Context) error {
	text := c.Args().First()
	if text == "" {
		return fmt.Errorf("Please provide memo text")
	}

	lastID++
	now := time.Now()
	memos = append(memos, Memo{ID: lastID, Text: text, CreatedAt: now, ModifiedAt: now})
	saveMemos() // 保存备忘录数据到文本文件
	fmt.Println("Memo added successfully")
	return nil
}

func listMemos(c *cli.Context) error {
	if len(memos) == 0 {
		fmt.Println("No memos found")
		return nil
	}

	fmt.Println("ID\tMemo\tCreated At\tModified At")
	for _, memo := range memos {
		fmt.Printf("%d\t%s\t%s\t%s\n", memo.ID, memo.Text, memo.CreatedAt.Format("2006-01-02 15:04:05"), memo.ModifiedAt.Format("2006-01-02 15:04:05"))
	}
	return nil
}

func deleteMemo(c *cli.Context) error {
	id := c.Int("id")
	if id <= 0 {
		return fmt.Errorf("Please provide a valid memo ID")
	}

	found := false
	for i, memo := range memos {
		if memo.ID == id {
			memos = append(memos[:i], memos[i+1:]...)
			found = true
			break
		}
	}

	if found {
		saveMemos() // 保存备忘录数据到文本文件
		fmt.Println("Memo deleted successfully")
	} else {
		fmt.Println("Memo not found")
	}

	return nil
}

func searchMemos(c *cli.Context) error {
	keyword := c.String("keyword")
	if keyword == "" {
		return fmt.Errorf("Please provide a keyword to search for")
	}

	found := false
	for _, memo := range memos {
		if strings.Contains(memo.Text, keyword) {
			fmt.Printf("ID: %d\tMemo: %s\n", memo.ID, memo.Text)
			found = true
		}
	}

	if !found {
		fmt.Println("No memos found matching the keyword")
	}

	return nil
}

func updateMemo(c *cli.Context) error {
	id := c.Int("id")
	if id <= 0 {
		return fmt.Errorf("Please provide a valid memo ID")
	}

	text := c.String("text")
	if text == "" {
		return fmt.Errorf("Please provide new text for the memo")
	}

	found := false
	for i, memo := range memos {
		if memo.ID == id {
			memos[i].Text = text
			memos[i].ModifiedAt = time.Now()
			found = true
			break
		}
	}

	if found {
		saveMemos() // 保存备忘录数据到文本文件
		fmt.Println("Memo updated successfully")
	} else {
		fmt.Println("Memo not found")
	}

	return nil
}

// 加载备忘录数据
func loadMemos() {
	file, err := os.OpenFile("memos.txt", os.O_RDONLY|os.O_CREATE, 0644)
	if err != nil {
		log.Fatal(err)
	}
	defer file.Close()

	scanner := bufio.NewScanner(file)
	for scanner.Scan() {
		line := scanner.Text()
		fields := strings.Split(line, "\t")
		if len(fields) != 4 {
			log.Printf("Invalid memo data: %s", line)
			continue
		}

		id, err := strconv.Atoi(fields[0])
		if err != nil {
			log.Printf("Invalid memo ID: %s", fields[0])
			continue
		}

		createdAt, err := time.Parse("2006-01-02 15:04:05", fields[2])
		if err != nil {
			log.Printf("Invalid created at time: %s", fields[2])
			continue
		}

		modifiedAt, err := time.Parse("2006-01-02 15:04:05", fields[3])
		if err != nil {
			log.Printf("Invalid modified at time: %s", fields[3])
			continue
		}

		memos = append(memos, Memo{
			ID:         id,
			Text:       fields[1],
			CreatedAt:  createdAt,
			ModifiedAt: modifiedAt,
		})
	}

	// 设置 lastID 为最大的备忘录项ID加1
	for _, memo := range memos {
		if memo.ID > lastID {
			lastID = memo.ID
		}
	}
}

// 保存备忘录数据到文本文件
func saveMemos() {
	file, err := os.OpenFile("memos.txt", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644) //写入模式
	if err != nil {
		log.Fatal(err)
	}
	defer file.Close()

	writer := bufio.NewWriter(file) //缓存数据，提高写入效率
	for _, memo := range memos {
		line := fmt.Sprintf("%d\t%s\t%s\t%s\n", memo.ID, memo.Text, memo.CreatedAt.Format("2006-01-02 15:04:05"), memo.ModifiedAt.Format("2006-01-02 15:04:05"))
		if _, err := writer.WriteString(line); err != nil {
			log.Println("Error writing memo:", err)
		}
	}

	if err := writer.Flush(); err != nil {
		log.Println("Error flushing writer:", err)
	}
}
